package com.sky.handler;

import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result exceptionHandler(BaseException e){
        log.error("异常信息：{}",e.getMessage());
        return Result.error(e.getMessage());
    }
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error("异常信息：{}",ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String username=ex.getMessage().split(" ")[2];
            return Result.error(username+"已存在");
        }else{
            return Result.error("未知错误");
        }
    }
}
